package org.example.bombermanserver.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.example.bombermanserver.model.Message;

import java.util.HashMap;
import java.util.Map;

public class ServerHandler extends SimpleChannelInboundHandler<Message> {

    // 保存所有客户端
    private static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 保存玩家位置
    private static final Map<String, int[]> playerPositions = new HashMap<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("客户端连接：" + ctx.channel().remoteAddress());
        channels.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("客户端断开：" + ctx.channel().remoteAddress());
        channels.remove(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) {
        System.out.println("收到消息：" + msg);

        switch (msg.getType()) {
            case "MOVE":
                // 更新玩家位置
                int x = msg.getX() != null ? msg.getX() : 0;
                int y = msg.getY() != null ? msg.getY() : 0;
                playerPositions.put(msg.getPlayerId(), new int[]{x, y});

                // 广播给所有客户端
                for (Channel c : channels) {
                    c.writeAndFlush(msg);
                }
                break;

            case "CHAT":
                // 简单回送
                Message response = new Message();
                response.setType("server-reply");
                response.setPlayerId("server-reply");
                response.setContent("recieved：" + msg.getPlayerId());
                ctx.writeAndFlush(response);
                break;

            default:
                System.out.println("未知消息类型：" + msg.getType());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
